package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.plant.bean.SpecDTO;
import com.yenlien.traceyun.plant.dao.ColdCategoryDao;
import com.yenlien.traceyun.plant.dao.ColdProductDao;
import com.yenlien.traceyun.plant.dao.ColdStorageCompDao;
import com.yenlien.traceyun.plant.entity.ColdCategory;
import com.yenlien.traceyun.plant.entity.ColdProduct;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Date 2022/9/28
 * @Author jiaLong
 * @Descript
 */

@Service
public class ColdProductService {

    @Autowired
    private ColdProductDao coldProductDao;

    @Autowired
    private ColdCategoryDao coldCategoryDao;

    //    @Autowired
//    private FileRestService fileRestService;
    @Autowired
    private ColdStorageCompDao coldStorageCompDao;


    public ColdProduct save(ColdProduct coldProduct) {
        if (CollectionUtils.isNotEmpty(coldProduct.getSpecDTOList()))
            coldProduct.setStockNum(coldProduct.getSpecDTOList().stream().collect(Collectors.summingInt(SpecDTO::getStockNum)));
        if (StringUtils.isEmpty(coldProduct.getCompanyName()) || StringUtils.isEmpty(coldProduct.getCompanyId())) {
            String companyId = UserAuthUtil.getLoginUser().getCompanyId();
            coldProduct.setCompanyId(companyId);
            coldProduct.setCompanyName(coldStorageCompDao.getById(companyId).getName());
        }
        coldProduct.setType("农贸".equals(coldProduct.getType()) ? "农资" : coldProduct.getType());
        return coldProductDao.save(coldProduct);
    }

    public void delById(String id) {
        coldProductDao.deleteById(id);
    }



    public static void tree(List<ColdCategory> coldCategoryList, String parentId, List<String> categoryList) {
        for (ColdCategory coldCategory : coldCategoryList) {
            if (parentId.equals(coldCategory.getParentId())) {
                categoryList.add(coldCategory.getLabel());
                tree(coldCategoryList, coldCategory.getId(), categoryList);
            }
        }
    }



    public Page<ColdProduct> findByList(ColdProduct coldProduct) {
        List<String> categoryList = new ArrayList<>();
        if (!StringUtils.isEmpty(coldProduct.getProductCategory())) {
            String id = coldCategoryDao.checkByLabel(coldProduct.getProductCategory());
            List<ColdCategory> coldCategoryList = coldCategoryDao.findAll();
            for (ColdCategory coldCategory : coldCategoryList) {
                if (!StringUtils.isEmpty(id) && id.equals(coldCategory.getId())) {
                    categoryList.add(coldCategory.getLabel());              // 包含自己
                    tree(coldCategoryList, coldCategory.getId(), categoryList);
                }
            }
        }


        Pageable pageable = PageRequest.of(coldProduct.getPage(), coldProduct.getPageSize());
        Page<ColdProduct> productPage = coldProductDao.findAll((Root<ColdProduct> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(coldProduct.getProductCategory())){
                // IN 当查询苹果类目时，那么该类目下的子类也应该被查出来
                CriteriaBuilder.In<String> productCategory = cb.in(root.get("productCategory"));
                for (String in : categoryList) {
                    productCategory.value(in);
                }
            }
            if (!StringUtils.isEmpty(coldProduct.getProductName()))
                list.add(cb.like(root.get("productName"), "%" + coldProduct.getProductName() + "%"));
            if (!StringUtils.isEmpty(coldProduct.getSaleState()))
                list.add(cb.equal(root.get("saleState"), coldProduct.getSaleState()));
            if (!StringUtils.isEmpty(coldProduct.getType()))
                list.add(cb.equal(root.get("type"), "农贸".equals(coldProduct.getType()) ? "农资" : coldProduct.getType()));
            if (!StringUtils.isEmpty(coldProduct.getCompanyId()))
                list.add(cb.equal(root.get("companyId"), coldProduct.getCompanyId()));
            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
        for (ColdProduct coldProduct1 : productPage.getContent()) {
            coldProduct1.setSpecDTOList(JSONObject.parseArray(coldProduct1.getSpec(), SpecDTO.class));
            DoubleSummaryStatistics collect = coldProduct1.getSpecDTOList().stream().collect(Collectors.summarizingDouble(x -> Double.parseDouble(x.getPrice())));
            coldProduct1.setPriceStart(String.valueOf(collect.getMin()));
            coldProduct1.setPriceEnd(String.valueOf(collect.getMax()));
        }
        return productPage;
    }

    public List<ColdProduct> findListNotPage(ColdProduct coldProduct) {
        List<String> categoryList = new ArrayList<>();
        if (!StringUtils.isEmpty(coldProduct.getProductCategory())) {
            String id = coldCategoryDao.checkByLabel(coldProduct.getProductCategory());
            List<ColdCategory> coldCategoryList = coldCategoryDao.findAll();
            for (ColdCategory coldCategory : coldCategoryList) {
                if (!StringUtils.isEmpty(id) && id.equals(coldCategory.getId())) {
                    categoryList.add(coldCategory.getLabel());              // 包含自己
                    tree(coldCategoryList, coldCategory.getId(), categoryList);
                }
            }
        }
        List<ColdProduct> coldProductList = coldProductDao.findAll((Root<ColdProduct> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(coldProduct.getProductCategory())){
                // IN 当查询苹果类目时，那么该类目下的子类也应该被查出来
                CriteriaBuilder.In<String> productCategory = cb.in(root.get("productCategory"));
                for (String in : categoryList) {
                    productCategory.value(in);
                }
                list.add(productCategory);
            }
            if (!StringUtils.isEmpty(coldProduct.getProductName()))
                list.add(cb.like(root.get("productName"), "%" + coldProduct.getProductName() + "%"));
            if (!StringUtils.isEmpty(coldProduct.getSaleState()))
                list.add(cb.equal(root.get("saleState"), coldProduct.getSaleState()));
            if (!StringUtils.isEmpty(coldProduct.getType()))
                list.add(cb.equal(root.get("type"), "农贸".equals(coldProduct.getType()) ? "农资" : coldProduct.getType()));
            if (!StringUtils.isEmpty(coldProduct.getCompanyId()))
                list.add(cb.equal(root.get("companyId"), coldProduct.getCompanyId()));
            return cb.and(list.toArray(new Predicate[list.size()]));
        });
        for (ColdProduct coldProduct1 : coldProductList) {
            coldProduct1.setSpecDTOList(JSONObject.parseArray(coldProduct1.getSpec(), SpecDTO.class));
            DoubleSummaryStatistics collect = coldProduct1.getSpecDTOList().stream().collect(Collectors.summarizingDouble(x -> Double.parseDouble(x.getPrice())));
            coldProduct1.setPriceStart(String.valueOf(collect.getMin()));
            coldProduct1.setPriceEnd(String.valueOf(collect.getMax()));
        }
        return coldProductList;
    }

}
